# -*- coding: utf-8 -*-
# @Time       : 2019/7/27 下午4:36
# @Author     : Simon
# @Email      : 
# @File       : api.py
# @Software   : PyCharm
# @Description:
import demjson

from Redis.redis import RedisConnect
from cron import dataPrepare4setTarget, setTargetexposurePer4Web, newSetTargetexposurePer4Web
from cron.job_func import addBusinessInfo
from db import getShopStatus, getMtShops, getShopLogs, getAccountById, getIdByName, getShopInfoNew, \
    getPeriodTarget, getPriceCount, upd_oprt_daily, \
    getShopBaseInfo, getHeadInfos, setShopCurbid, addANewShop, deleteTodayTarget, adminLogin, \
    adminSign, decryptShopId, checkManager, setShopPrice, closeShopBidding, \
    testGetAllShops, getShopOrder, getCurrentOrder, getAllBiddingShops, getShopCookieByShopId, changeDeletedVal, Admin, \
    setShopInfo, getShopInfoforSet, getShopPeriodCurbid, changeHistoryVal, newGetPriceCount, newGetPeriodTarget, \
    newGetPeriod7DaysOrder, getShopInfoforNewSet, new_set_shop, changeShopBudget, getPeriod7DaysOrder, setmode2, \
    getmode1, getmode2, getmode3, setmode3, getmode4, setmode4, saveShop, getShopidInfo, setNewShopBaseInfo, \
    setBusyandIdle, getdata7, setdata7, getCurbidCount, getStatusMode, setStatusMode, saveTomorrowPara, \
    getAppPriceCount, getPeriod7DaysOrderHour, getPeriodTargetHour, mode2_set_for_mobile, judge_new_shop, checkUser, \
    getTargetBidding, updShopInfo, updeleCookie, updMtCookie, getShopBiddingReplenishNum, Pool, redis, userRegister, \
    Session, decryptShopIdwithsession, ShopMeituanInfo, ShopEleInfo, getShopBaseInfowithShopInfo, \
    getHeadInfoswithShopInfo, getPriceCountwithSessionwithShopInfo, getPeriodTargetwithSession, \
    getPeriod7DaysOrderwithSession, getShopReportHeadInfo, getReportInfo, getIdleMaxPrice, reportCheck, \
    getYesReportData, getResearchData, getShopInfoNewWeb, getNextExposureRate, getExposureRate, saveAllExposureRate, \
    saveSettings, newGetShopOrder, checkBuckupIp, changeNewIp, setMobileMode2SetCopy, changeDeletedShopStatus
from web.report import getAllShopLastDayReportData
from web.service.api_service.admin.biddingService import getBiddingsData, bindShopAccount
from web.service.api_service.charts.chart_service import changeNewCustomPrice, getNewCustomPrice, getallTime, \
    bindAdminShopApi, getAllShopInfo
from web.service.api_service.public.check import serviceApiCheck

from web.service.overData.sql_db import updShopInfoNew, getMyShop, setSuggestParam, setSuggestParamLoad, \
    addPlansOfShops, getMOrEBsaeInfo, closeOrOpenShopBidding, changeShopGuard, loadShopNote, \
    updShopNote, getShopBiddingYester, getYesOrderInfo, updLastShopBidding, getMyShopBlance, updShopInfoOfLock, \
    getYesOrderInfowithSession, getShopBiddingYesterwithSession, saveBiddingDataToBases, getAccountByIdAndShopType, \
    updShopNoteRedis

from . import app, request, jsonify, make_response
from config import config

import hashlib

import datetime
import traceback
from LoggerWarpper import logger
from decimal import Decimal
import time
import urllib

import json
from flask_cors import CORS

from .service.api_service.public.service import getMtShopIpInfo

CORS(app, supports_credentials=True)


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


@app.before_request
def before_request():
    request_path = request.path
    if request_path not in config.SAVE_LIST:
        return
    request_param = None
    if request.method == 'GET':
        request_param = request.values.to_dict()
    else:
        request_param = request.get_json()
    upd_oprt_daily(request_path, request_param)

@app.route("/api/v1/user/signup", methods=["POST", "GET"])
def sign():
    '''
    用户注册
    :return:
    '''
    logger.debug(request.values)
    response = config.RESPONSE
    try:
        salt = int(time.time() * 1000)
        user = request.values.get("user")
        pwd = request.values.get("pwd")
        masterid = request.values.get("masterid")
        openId = request.values.get("openid")
        pwdmd5 = hashlib.md5((str(pwd) + str(salt)).encode(encoding='UTF-8')).hexdigest()
        phone = request.values.get("phone")
        realname = request.values.get("realname")
        realname = user
        result = userRegister(user, pwdmd5,
                              **dict(phone=phone, realname=realname, salt=salt, masterid=masterid, openId=openId))
        if result == config.SUCCESS:
            response.update(code=200, message=config.RESPONSE_SUCCESS, data="")
        elif result == config.FAIL_USER:
            response.update(code=403, message=config.RESPONSE_FAIL, data="")
        else:
            response.update(code=500, message=config.RESPONSE_PENDING, data="")
        logger.debug(response)
        return jsonify(response)
    except:
        response.update(code=500, message=config.RESPONSE_PENDING, data="")
        logger.debug(response)
        return jsonify(response)


@app.route("/api/v1/getShopOrder", methods=['GET'])
def get_shop_order():
    response = config.RESPONSE
    sid = request.values.get("id")
    result = getShopOrder(sid=sid)
    response.update({"code": 200, "message": "成功", "data": result})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/checkOut")
def checkOut():
    '''1、获取所有需要推广的店铺'''
    try:
        allShops = getAllBiddingShops(0)
        '''2、查看所有需要推广的店铺的竞价计划是否生成'''
        allShops = addPlansOfShops(allShops)
        response = dict(code=200, message=config.RESPONSE_SUCCESS, data=allShops)
    except:
        response = dict(code=500, message="获取失败", data=None)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route('/api/v1/shop/getCurrentOrder', methods=['GET'])
def get_current_order():
    response = config.RESPONSE
    sid = request.values.get("id")
    index = request.values.get("index")
    result = getCurrentOrder(sid, index)
    if result:
        response.update({"code": 200, "message": "获取成功", "data": result})
    else:
        response.update({"code": 500, "message": "获取失败", "data": None})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response



@app.route("/api/v1/getAllShop", methods=['GET'])
def get_mt_shop():
    response = config.RESPONSE
    result = getMtShops()
    if result == [[], []]:
        response.update({"code": 500, "message": "获取店铺列表失败", "data": result})
    else:
        response.update({"code": 200, "message": "获取店铺列表成功", "data": result})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/getShopLogs", methods=['GET'])
def get_shop_logs():
    response = config.RESPONSE
    sid = request.values.get("id")
    query_time = request.values.get("time")
    if not query_time:
        timestart = datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00"
        timeend = (datetime.datetime.now() + datetime.timedelta(days = 1)).strftime("%Y-%m-%d") + " 00:00:00"
    else:
        d = query_time.split("-")[2]
        d2 = query_time.split("-")[1]
        if int(d) < 10:
            d = '0' + d
            query_time = query_time.split('-')[0] + "-" + query_time.split('-')[1] + "-" + d

        if int(d2) < 10:
            d2 = '0' + d2
            query_time = query_time.split('-')[0] + "-" + d2 + "-" + d
        timestart = datetime.datetime.strptime(query_time+" 00:00:00","%Y-%m-%d 00:00:00")
        timeend = (timestart + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
        timestart = query_time + " 00:00:00"

    result = getShopLogs(sid,timestart,timeend)
    response.update({"code":200, "message": "成功", "data": result})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/user/login", methods=["POST", "GET"])
def login():
    '''
    用户登录
    :return:
    '''
    logger.debug(request.values)
    response = config.RESPONSE
    try:
        user = request.values.get("user")
        pwd = request.values.get("pwd")
        # pwdmd5=hashlib.md5(pwd.encode(encoding='UTF-8')).hexdigest()
        result = checkUser(user, pwd)
        code = result.get("code")
        realname = result.get("realname", '')
        salt = result.get("salt")
        # salt='e10adc3949ba59abbe56e057f20f883e'
        if code == config.FAIL_USER:
            response = dict(code=404, message="账号不存在", data="")
        elif code == config.FAIL_PWD:
            response.update(code=500, message="密码错误", data="")
        elif code == config.FAIL_EXPIRE:
            response.update(code=403, message="账号过期", data="")
        elif code == config.SUCCESS:
            response.update(code=200, message=config.RESPONSE_SUCCESS, data="")
            resp = make_response(jsonify(response))
            resp.set_cookie('bid', salt)
            resp.set_cookie('realname', urllib.parse.quote(realname))
            logger.debug(resp)
            return resp
        else:
            response.update(code=500, message=config.RESPONSE_PENDING, data="")
        logger.debug(response)
        return jsonify(response)
    except:
        logger.error(traceback.format_exc())
        response.update(code=500, message=config.RESPONSE_PENDING, data="")
        logger.debug(response)
        return jsonify(response)


@app.route("/api/v1/findshop", methods=['GET'])
def findshop():
    try:
        findby = request.values.get("findby")
        shoptype = request.values.get("type")
        result = None
        if findby.isdigit():
            if getAccountById(findby):

                result = dict(code=200, messae='查找成功', data=findby)
            else:
                result = dict(code=404, messae='没有该店铺', data=traceback.format_exc())
        else:
            findby = findby.strip()
            id = getIdByName(findby, shoptype)
            if id:
                result = dict(code=200, messae='查找成功', data=id)
            else:
                result = dict(code=404, messae='没有该店铺', data=traceback.format_exc())
        response = make_response(jsonify(result))
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
        return response
    except:
        logger.error(traceback.format_exc())
        return jsonify(dict(code=500, messae='未知错误', data=traceback.format_exc()))


@app.route("/api/v1/bidding/target/getplans", methods=['GET'])
def getplans():
    try:
        id = request.values.get("id")
        account, type = getAccountById(id)
        try:
            targetnum = getTargetBidding(account=account, type=type)
            response = dict(code=200, messae="获取成功", data=targetnum)
        except:
            response = dict(code=500, messae="获取失败", data=None)
        response = make_response(jsonify(response))
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
        return response

    except:
        logger.error(traceback.format_exc())
        return jsonify(dict(code=500, messae='未知错误', data=traceback.format_exc()))


@app.route("/api/v1/shop/add", methods=["POST"])
def shopadd():
    logger.debug(request.values)

    try:

        shopid = request.values.get("shopid")
        mtadtime = request.values.get("mtadtime")
        eleadtime = request.values.get("eleadtime")
        mtaccount = request.values.get("mtaccount")

        eleaccount = request.values.get("eleaccount")

        mtbudget = request.values.get('mtbudget', 0)
        mtisenable = request.values.get("mtisenable", 0)
        mttargetExposure = request.values.get("mttargetexposure", 0)

        idleExposureRate = request.values.get("idleExposureRate",1.45)

        elebudget = request.values.get("elebudget", 0)
        eleisenable = request.values.get("eleisenable", 0)
        eletargetexposure = request.values.get("eletargetexposure", 0)


        os = request.values.get("os")
        percent = request.values.get("percentList", "")
        specialtime = request.values.get("specialtime", "")
        keepSameStatus = request.values.get("keepSameStatus", "")
        serviceTime = request.values.get("serviceTime")

        idleOrderRateList = request.values.get("idleOrderRateList")
        busyOrderRate = request.values.get("busyOrderRate")
        daysAvgPrice = request.values.get("daysAvgPrice")
        immediate = request.values.get("immediate")

        busyTimeLock =  request.values.get("busyTimeLock")
        controlRate  = request.values.get("controlRate")
        baseRate = request.values.get("baseRate")

        createPlan = request.values.get("createPlan")

        nextExposureRate = request.values.get("nextExposureRate")
        allExposureRate = request.values.get("allExposureRate")


        if keepSameStatus == 'true':
            keepSameStatus = 1
        else:
            keepSameStatus = 0

        kwargs = dict(
                      mtbudget=mtbudget,
                      mtisenable=mtisenable,
                      mttargetExposure=mttargetExposure,
                      idleOrderRateList=idleOrderRateList,
                      busyOrderRate=busyOrderRate,
                      daysAvgPrice = daysAvgPrice,
                      mtaccount=mtaccount,
                      eleaccount=eleaccount,

                      busyTimeLock = busyTimeLock,
                      controlRate = controlRate,
                      baseRate = baseRate,

                      elebudget=elebudget,
                      eleisenable=eleisenable,
                      eletargetExposure=eletargetexposure,
                      shopid=shopid,
                      mtadtime=mtadtime,
                      eleadtime=eleadtime,
                      os=os,
                      percent=percent,
                      specialtime=specialtime,
                      keepSameStatus=keepSameStatus,
                      serviceTime=serviceTime,
                      idleExposureRate = idleExposureRate,
                      nextExposureRate = nextExposureRate,
                      allExposureRate = allExposureRate,
                      )
        if immediate == '1':
            updShopInfo(**kwargs)
        else:
            saveTomorrowPara(**kwargs)

        if createPlan == "1":
            try:
                account = None
                shopType = 0
                adTime = None
                targetExposure = None
                budget = None
                if mtaccount:
                    account = mtaccount
                    shopType = 1
                    adTime = mtadtime
                    targetExposure = mttargetExposure
                    budget = mtbudget
                elif eleaccount:
                    account = eleaccount
                    shopType = 2
                    adTime = eleadtime
                    targetExposure = eletargetexposure
                    budget = elebudget

                nextExposureRate = getNextExposureRate(account, int(shopType))
                deleteTodayTarget(account, int(immediate))
                data = dataPrepare4setTarget(account, adTime, shopType, targetExposure, budget, int(immediate))
                setTargetexposurePer4Web(data, shopType,nextExposureRate)

            except:
                logger.warning(traceback.format_exc())
                response = dict(code=500, message="保存失败", data="")
                return jsonify(response)

        response = dict(code=200, message="保存成功", data=1)
        logger.debug(response)
        return jsonify(response)

    except:
        logger.error(traceback.format_exc())
        response = dict(code=500, message="保存失败", data="")
        return jsonify(response)


@app.route("/api/v1/shop/getNew", methods=["GET"])
def getshopNew():
    '''
    获取商铺信息
    :param shopid:
    :return:
    '''
    logger.debug(request.values)
    response = config.RESPONSE
    cookies = request.cookies
    bid = cookies.get("bid")
    if not bid:
        response = dict(code='403', message="用户不存在", data="")
        return jsonify(response)
    shopid = request.values.get("shopid")
    shoplist = getShopInfoNew(bid, **dict(shopid=shopid))
    if shoplist == config.PENNDING_ERROR:
        response = dict(code=500, message=config.RESPONSE_FAIL, data="")
    else:
        response = dict(code=200, message=config.RESPONSE_SUCCESS, data=shoplist)
    logger.debug(response)
    return jsonify(response)


@app.route("/api/v1/log/handle", methods=['POST', 'GET'])
def cookiehandle():
    logger.debug(request.values)
    response = config.RESPONSE
    mtcookie = request.values.get("mtcookie")
    mtaccount = request.values.get("mtaccount")
    eleksid = request.values.get("eleksid")
    eleaccount = request.values.get("eleaccount")
    eleshopid = request.values.get("eleshopid")
    if eleksid:
        updeleCookie(eleaccount, eleksid, eleshopid)
    if mtaccount:
        updMtCookie(mtaccount, mtcookie)
    response.update({"code": 200, "message": "成功"})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/getSuggestParam")
def getSuggestParam():
    '''获取'给前端的接口数据'''
    shopId = int(request.values.get("shopId"))
    shopType = int(request.values.get("shopType"))
    try:
        result = setSuggestParam(shopId, shopType)
        if not result:
            result = setSuggestParamLoad(shopId, shopType)
        response = dict(code=200, message="建议值获取成功", data=result)
    except:
        response = dict(code=500, message="建议值获取失败", data=None)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/getSuggestParamLoad")
def getSuggestParamLoad():
    shopId = int(request.values.get("shopId"))
    shopType = int(request.values.get("shopType"))
    result = setSuggestParamLoad(shopId, shopType)
    response = dict(code=200, message=config.RESPONSE_SUCCESS, data=result)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response




@app.route("/api/v1/shop/getMeun", methods=["GET"])
def getShopNew():
    mtId = request.values.get("mtId")
    eleId = request.values.get("eleId")
    if (not mtId) and (not eleId):
        response = dict(code='403', message="店铺信息不完整，请先刷新店铺", data="")
    else:
        shoplist = getShopInfoNew(**dict(mtId=mtId, eleId=eleId))
        if shoplist == 500:
            response = dict(code=500, message="获取店铺信息失败", data="")
        else:
            if shoplist[0].get("invalidLogon"):
                response = dict(code=500, message="Cookies失效", data = shoplist)
            else:
                response = dict(code=200, message="获取店铺信息成功", data=shoplist)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/shop/newGetShopInfo", methods=["GET"])
def getShopNewWeb():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shoplist = getShopInfoNewWeb(int(shopId),int(shopType))
    if shoplist == 500:
        response = dict(code=500, message="获取店铺信息失败", data="")
    else:
        response = dict(code=200, message="获取店铺信息成功", data=shoplist)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/get", methods=["GET"])
def getshop():
    '''
    获取商铺信息
    :param shopid:
    :return:
    '''

    shopId = request.values.get("shopId", "")
    originalShopId = shopId
    shopType = int(request.values.get("shopType", ""))
    app = int(request.values.get("app", 0))
    session = Session()

    # 获取解密的shopId
    shopId = decryptShopIdwithsession(session,shopId,shopType)

    eleShop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mtShop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()

    #r = redis.Redis(connection_pool=Pool, decode_responses=True)

    #result = r.get(originalShopId)
    #if not result:

    # 获取日期
    date = request.values.get("date", "")
    if date:
        date = date + " 00:00:00"
    else:
        date = datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00"

    if not date:
        dateDay = datetime.datetime.now().strftime("%Y-%m-%d")
    else:
        dateDay = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")

    shopBaseInfo = getShopBaseInfowithShopInfo(eleShop,mtShop, shopType)
    headInfo = getYesOrderInfowithSession(session,shopBaseInfo.get('account', ""), day=dateDay)

    if headInfo:
        headInfo = eval(headInfo)
        heads = {"item1": {"showCount": headInfo.get('ep', {}).get('o', None),
                           "targetExposure": headInfo.get('ep', {}).get('t', None)},
                 "item2": {"clickCount": headInfo.get('ck', {}).get('o', None),
                           "daysAvgClickCount": headInfo.get('ck', {}).get('s', None)},
                 "item3": {"currentCost": headInfo.get('cot', {}).get('p', None),
                           "todayBudget": int(headInfo.get('cot', {}).get('x', None)), "daysAvgCost": None},
                 "item4": {"avgPrice": headInfo.get('pc', {}).get('o', None),
                           "daysAvgPrice": headInfo.get('pc', {}).get('s', None)}}
    else:
        heads = getHeadInfoswithShopInfo(eleShop,mtShop, int(shopType))
#到此处，上部分所有爬虫没写，在java中均有备注
    biddingInfo = getPriceCountwithSessionwithShopInfo(session,eleShop,mtShop,shopId , shopType, date, app)
    yesDateTime = (datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=-1)).strftime(
        "%Y-%m-%d %H:%M:%S")

    yesBiddingInfo = getPriceCountwithSessionwithShopInfo(session,eleShop,mtShop,shopId , shopType, yesDateTime, app)

    periodTarget = getPeriodTargetwithSession(session,shopId, shopType, date) #2
    try:
        orderResult = getPeriod7DaysOrderwithSession(session, originalShopId, shopType)  # 3
    except:
        orderResult = {}
    sevenDaysAvgOrders = orderResult.get("hourOrderNumOfSeven")
    daysAvgNum = orderResult.get("orderNumOfSeven")
    table1 = {"hourPriceCounts": biddingInfo.get("hourPriceCounts", {}),"periodCost":None,
              "allDayPriceCounts": biddingInfo.get("allDayPriceCounts", {}),
              "masterData": biddingInfo.get("masterData", {}), "cost": None}
    table1Copy = {"hourPriceCounts": yesBiddingInfo.get("hourPriceCounts", {}),
                  "allDayPriceCounts": yesBiddingInfo.get("allDayPriceCounts", {}),
                  "masterData": yesBiddingInfo.get("masterData", {}), "cost": None}
    table2 = {"allExposure": None, "periodExposure": biddingInfo.get("periodExposure", []),
              "periodTarget": periodTarget}
    table2Copy = {"allExposure": None, "periodExposure": yesBiddingInfo.get("periodExposure", []),
                  "periodTarget": None}
    table3 = {"allrealTimeOrder": None, "sevenDaysAvgOrders": sevenDaysAvgOrders,
              "dayRealTimeOrder": biddingInfo.get("realTimeOrderList", [])}
    table4 = {"yesNum": None, "daysAvgNum": daysAvgNum}
    busyTime = biddingInfo.get("busyTime", [])
    #4

    # start3 = time.time()
    # redis_data = json.loads(r.get(originalShopId))
    # table1 = redis_data.get("table1")
    # table2 = redis_data.get("table2")
    # table1Copy = redis_data.get("table1Copy")
    # table2Copy = redis_data.get("table2Copy")
    # table3 = redis_data.get("table3")
    # table4 = redis_data.get("table4")
    # busyTime = redis_data.get("busyTime")
    # end3 = time.time()
    # print("取:{}".format(end3 - start3))

    if date:
        today_time = dateDay
    else:
        today_time = datetime.datetime.now().strftime("%Y-%m-%d")
    tommorrowList = datetime.datetime.strptime(today_time, "%Y-%m-%d")
    tommorrow_time = (tommorrowList + datetime.timedelta(days=+1)).strftime("%Y-%m-%d") + " 00:00:00"
    lastShopBidding = getShopBiddingYesterwithSession(session,shopId, tommorrow_time, shopType)
    yesLastShopBidding = getShopBiddingYesterwithSession(session,shopId, today_time + " 00:00:00", shopType)
    response = None
    if yesLastShopBidding and lastShopBidding:
        if lastShopBidding.id == yesLastShopBidding.id:
            response = dict(code=200, message="当前数据为空", data="")
    elif lastShopBidding == None:
        response = dict(code=200, message="当前数据为空", data="")
    data = None
    if lastShopBidding:
        table1["cost"] = round(float(lastShopBidding.currentCost), 2)
        table1["periodCost"] =  round(float(lastShopBidding.directPrice), 2)
        table2["allExposure"] = int(lastShopBidding.exposureNum)
        table3["allrealTimeOrder"] = int(lastShopBidding.realTimeOrder)
        if not yesLastShopBidding:
            yesNum = orderResult.get("yesNum")
            table4['yesNum'] = yesNum
        else:
            table4['yesNum'] = int(yesLastShopBidding.realTimeOrder)
        data = {"table1": table1, "table2": table2, "table3": table3, "table4": table4, "headInfo": heads,
                "shopBaseInfo": shopBaseInfo, "busyTime": busyTime,
                "table1Copy": table1Copy, "table2Copy": table2Copy}

    #redis_data = demjson.encode(data)

    #r.set(originalShopId, redis_data)
    # else:
    #     data = demjson.decode(result)

    response = dict(code=200, message=config.RESPONSE_SUCCESS, data=data)

    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'

    return response


@app.route("/api/v1/saveNewShop", methods=['GET'])
def saveNewShop():
    name = request.values.get("name")
    account = request.values.get("account")
    maxPrice = request.values.get("maxPrice")
    minPrice = request.values.get("minPrice")
    isEnable = request.values.get("isEnable")
    isBind = request.values.get("isBind")
    budget = request.values.get("budget")
    targetExposure = request.values.get("targetExposure")
    isByBudget = request.values.get("isByBudget")
    shopType = request.values.get("shopType")  # str
    manager = request.values.get("manager")
    shopData1 = {"name": name,
                 "account": account,
                 "shopType": shopType,
                 "isenable": isEnable,
                 "isbind": isBind,
                 "username": manager,
                 "targetExposure": targetExposure,
                 "budget": budget}
    shopData2 = {
        "minprice": minPrice,
        "maxprice": maxPrice
    }
    res = checkManager(manager)
    if res == 1000:
        response = dict(code=200, message="该管理账号不存在", data="")
    elif not res:
        response = dict(code=200, message="未知错误", data="")
    else:
        result = addANewShop(shopData1, shopData2, shopType)
        if result == 1000:
            response = dict(code=200, message="该店铺已经存在", data="")
        else:
            response = dict(code=200, message="添加成功", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/getNewAllShop", methods=['GET'])
def getNewAllShop():
    response = config.RESPONSE
    try:
        bid = request.values.get("bid")
        day = request.values.get("day")
        result = getMyShop(bid, day)
        if result == 1000:
            response.update({"code": 200, "message": "该账号没有绑定店铺", "data": False})
        if result == False:
            response.update({"code": 200, "message": "数据错误", "data": False})
        else:
            response.update({"code": 200, "message": "成功", "data": result})
    except:
        response.update({"code": 200, "message": "未知错误", "data": "fail"})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/adminLogin", methods=['GET'])
def admin_login():
    username = request.values.get("username")
    pwd = request.values.get("pwd")
    result = adminLogin(username, pwd)
    response = dict(code=200, message=config.RESPONSE_SUCCESS, data=result)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/adminSign", methods=['GET'])
def admin_sign():
    # data = request.get_data().decode('utf-8')
    # data = json.loads(data)
    username = request.values.get("username")
    pwd = request.values.get("pwd")
    result = adminSign(username, pwd)
    if not result:
        response = dict(code=2000, message=config.RESPONSE_SUCCESS, data=result)
    else:
        response = dict(code=200, message=config.RESPONSE_SUCCESS, data=result)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/setPrice", methods=["GET"])
def shopSetPrice():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    price = request.values.get("price")
    res = setShopPrice(int(shopType), shopId, float(price))
    shop_id = decryptShopId(shopId, int(shopType))
    updLastShopBidding(*[shop_id, shopType], **dict(replenishnum=1))
    response = None
    if res:
        response = dict(code=200, message="设置成功", data="")
    else:
        response = dict(code=200, message="设置失败", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/close", methods=["GET"])
def closeShop():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    res = closeShopBidding(shopId, shopType)
    response = None
    if res:
        response = dict(code=200, message="关闭成功", data="")
    else:
        response = dict(code=200, message="关闭失败", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/testGet", methods=["GET"])
def testGetShop():
    bid = request.values.get("bid")
    res = testGetAllShops()
    response = dict(code=200, message="关闭失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/updShopInfo")
def updNewShopInfo():
    shopId = int(request.values.get("shopId"))
    shopType = int(request.values.get("shopType"))
    shopCookies = getShopCookieByShopId(shopId, shopType)
    '''1、获取店铺的推广状态和营业时间'''
    shopInfo = getMOrEBsaeInfo(shopType, shopCookies, None)
    updShopInfoNew(**dict(shopId=shopId, shopType=shopType, shipTime=shopInfo.get("date").get("shipTime")))
    response = dict(code=200, message=config.RESPONSE_SUCCESS, data=shopInfo)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/closeOrOpenShop")
def closeOrOpenShop():
    '''
    关闭或者打开推广
    :return:
    '''
    try:
        shopId = request.values.get("shopId")  # 都是用的加密的shopId
        shopType = int(request.values.get("shopType"))
        status = int(request.values.get("status", 0))  # 默认是关闭，1是打开
        if not shopId or not shopType:
            # 缺少参数
            response = dict(code=200, message=config.PARAM_ERROR, data=config.PARAM_ERROR_CODE)
        else:
            res = closeOrOpenShopBidding(shopId, shopType, status)
            if res:
                response = dict(code=200, message=config.RESPONSE_SUCCESS, data=config.SUCCESS)
            else:
                response = dict(code=200, message=config.RESPONSE_FAIL, data=config.FAIL)
    except:
        response = dict(code=200, message=config.RESPONSE_PENDING, data=config.FAIL)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/getDeletedShop")
def getDeletedShop():
    '''1、获取所有需要推广的店铺'''
    allShops = getAllBiddingShops(1)
    response = dict(code=200, message=config.RESPONSE_SUCCESS, data=allShops)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/changeDeletedVal")
def changeDeletedStatus():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    deleted = request.values.get("deleted")
    res = changeDeletedVal(int(shopId), int(shopType), int(deleted))
    if res:
        response = dict(code=200, message="执行成功", data="")
    else:
        response = dict(code=500, message="执行失败", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/delete")
def changeDeletedStatus2():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    deleted = 1
    res = changeDeletedVal(int(shopId), int(shopType), deleted)
    if res:
        response = dict(code=200, message="执行成功", data=1)
    else:
        response = dict(code=500, message="执行失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/changeGuard")
def changeGuard():
    shopId = int(request.values.get("shopId"))
    shopType = int(request.values.get("shopType"))
    status = int(request.values.get("status"))  # 0、关闭监测系统  1、打开监测系统
    result = changeShopGuard(shopId, shopType, status)
    if result:
        response = dict(code=200, message=config.RESPONSE_SUCCESS, date=config.SUCCESS)
    else:
        response = dict(code=200, message=config.RESPONSE_FAIL, date=config.FAIL)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/set", methods=["GET"])
def shopSet():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    busyTime = request.values.get("busyTime")

    busyMaxPrice = request.values.get("busyMaxPrice")
    busyMinPrice = request.values.get("busyMinPrice")
    idleMaxPrice = request.values.get("idleMaxPrice")
    idleMinPrice = request.values.get("idleMinPrice")
    budget = request.values.get("budget")
    busy = {}
    busy['busyMaxPrice'] = busyMaxPrice
    busy['busyMinPrice'] = busyMinPrice
    busy['idleMaxPrice'] = idleMaxPrice
    busy['idleMinPrice'] = idleMinPrice
    busy['busyTime'] = busyTime

    res = setShopInfo(shopId, int(shopType), busy, float(budget))
    if res:
        response = dict(code=200, message="设置成功", data=1)
    else:
        response = dict(code=200, message="设置失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/getShopSetInfo")
def getShopSetInfo():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    res = getShopInfoforSet(shopId, int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=200, message="暂无数据", data=[])
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/getHisCurbid")
def getShopCurbid():
    shopId = int(request.values.get("shopId"))
    shopType = int(request.values.get("shopType"))
    date = request.values.get("date")
    res = getShopPeriodCurbid(shopId, shopType, date)
    if res == 1000:
        response = dict(code=404, message="无该日数据", data=0)
    else:
        response = dict(code=200, message="成功", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/changeHistoryMode")
def changeHistoryMode():
    shopId = request.values.get("shopId")
    shopType = int(request.values.get("shopType"))
    historymode = int(request.values.get("historymode"))
    date = request.values.get("date")
    res = changeHistoryVal(shopId, shopType, date, historymode)
    if res == 1000:
        response = dict(code=404, message="无该日数据", data=0)
    elif not res:
        response = dict(code=500, message="未知错误", data=-1)
    else:
        response = dict(code=200, message="成功", data=1)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/newget", methods=["GET"])
def newGetShop():
    '''
    获取商铺信息
    :param shopid:
    :return:
    '''
    try:
        shopId = request.values.get("shopId", "")
        originalShopId = shopId
        shopType = int(request.values.get("shopType", ""))
        app = int(request.values.get("app", 0))
        # 获取解密的shopId
        shopId = decryptShopId(shopId, shopType)
        # 获取日期
        date = request.values.get("date", "")
        if date:
            if date == datetime.datetime.now().date().strftime("%Y-%m-%d"):
                date = ""
            else:
                date = date + " 00:00:00"

        biddingInfo = newGetPriceCount(shopId, shopType, date, app)
        periodTarget = newGetPeriodTarget(shopId, shopType, date)
        orderResult = newGetPeriod7DaysOrder(originalShopId, shopType)
        sevenDaysAvgOrders = orderResult.get("hourOrderNumOfSeven")
        yesNum = orderResult.get("yesNum")
        daysAvgNum = orderResult.get("orderNumOfSeven")
        try:
            heads = getHeadInfos(int(shopId), int(shopType))
        except:
            heads = None
        table1 = {"hourPriceCounts": biddingInfo.get("hourPriceCounts", {}),
                  "allDayPriceCounts": biddingInfo.get("allDayPriceCounts", {}),
                  "masterData": biddingInfo.get("masterData", {}), "cost": None}
        table2 = {"allExposure": None, "periodExposure": biddingInfo.get("periodExposure", []),
                  "periodTarget": periodTarget}
        table3 = {"allrealTimeOrder": None, "sevenDaysAvgOrders": sevenDaysAvgOrders,
                  "dayRealTimeOrder": biddingInfo.get("realTimeOrderList", [])}
        table4 = {"yesNum": yesNum, "daysAvgNum": daysAvgNum}
        shopBaseInfo = getShopBaseInfo(originalShopId, shopType)

        if date:
            today_time = date + " 00:00:00"
        else:
            today_time = datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00"
        lastShopBidding = getShopBiddingReplenishNum(shopId, today_time, shopType)
        if lastShopBidding == None:
            response = dict(code=200, message="当前数据为空", data="")
        else:
            table1["cost"] = lastShopBidding.currentCost
            table2["allExposure"] = lastShopBidding.exposureNum
            table3["allrealTimeOrder"] = lastShopBidding.realTimeOrder
            # headInfo={"exposure":lastShopBidding.exposureNum,"businessAmount":lastShopBidding.businessAmount,"realTimeOrder":lastShopBidding.realTimeOrder,"cost":round(float(lastShopBidding.todayBudget)*float(lastShopBidding.percentBudget),2)}
            data = {"table1": table1, "table2": table2, "table3": table3, "table4": table4, "headInfo": heads,
                    "shopBaseInfo": shopBaseInfo, "busyTime": biddingInfo.get("busyTime", [])}
            response = dict(code=200, message=config.RESPONSE_SUCCESS, data=data)
    except:
        response = dict(code=200, message="当前暂无数据", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/newShopGet", methods=["GET"])
def newShopGet():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    res = getShopInfoforNewSet(shopId, int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=200, message="暂无数据", data=[])
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


'''新服务器的日志接口'''


@app.route("/api/v1/chart/shop/setNote", methods=["GET"])
def setNote():
    try:
        shopId = request.values.get("shopId")
        shopType = int(request.values.get("shopType"))
        note = request.values.get("note")
        # day=request.values.get("day")
        # 获取解密的shopId
        shopId = decryptShopId(shopId, shopType)
        result = updShopNote(shopId, shopType, note)
        result_redis = updShopNoteRedis(shopId, shopType, note)
        if result and result_redis:
            response = dict(code=200, message=config.RESPONSE_SUCCESS, data=config.SUCCESS)
        else:
            response = dict(code=200, message=config.RESPONSE_FAIL, data=config.FAIL)
    except:
        response = dict(code=200, message=config.RESPONSE_FAIL, data=config.FAIL)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


'''新服务器的日志接口'''


@app.route("/api/v1/chart/shop/getNote", methods=["GET"])
def getNote():
    try:
        shopId = request.values.get("shopId")
        shopType = int(request.values.get("shopType"))
        day = request.values.get("day")
        # 获取解密的shopId
        shopId = decryptShopId(shopId, shopType)
        result = loadShopNote(shopId, shopType, day)
        if result == 1000:
            response = dict(code=200, message="今天暂无备注", data='')
        elif result:
            response = dict(code=200, message=config.RESPONSE_SUCCESS, data=result)
        else:
            response = dict(code=200, message=config.RESPONSE_FAIL, data=config.FAIL)
    except:
        response = dict(code=200, message=config.RESPONSE_FAIL, data=config.FAIL)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response





@app.route("/api/v1/admin/shop/changeBudget")
def changeBudget():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    budget = request.values.get("budget")
    # 开关打开设置平台预算和我们的预算一值
    res = changeShopBudget(int(shopId), int(shopType), int(budget) * 100)
    if res:
        response = dict(code=200, message="执行成功", data=1)
    else:
        response = dict(code=200, message="执行失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


##第一个模块，set&get
@app.route("/api/v1/admin/shop/mode1set")
def mode1set():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    budget = request.values.get("budget")
    status = request.values.get("status")
    shopId = decryptShopId(shopId, int(shopType))
    # 设置预算
    res = None
    res2 = None
    try:
        res = changeShopBudget(int(shopId), int(shopType), int(budget) * 100)
    except:
        logger.error(traceback.format_exc())
        logger.info("{}修改店铺平台预算失败".format(shopId))
    try:
        res2 = closeOrOpenShopBidding(int(shopId), int(shopType), int(status))
    except:
        logger.error(traceback.format_exc())
        logger.info("{}打开关闭平台推广开关失败".format(shopId))

    if res and res2:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode1get")
def mode1get():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    res = None
    ##营业时间和推广状态获取
    shopCookies = getShopCookieByShopId(int(shopId), int(shopType))
    status = ''
    shipTime = ''
    if shopCookies:
        try:
            shopInfo = getMOrEBsaeInfo(int(shopType), shopCookies, None).get("date")
            updShopInfoNew(**dict(shopId=shopId, shopType=shopType, shipTime=shopInfo.get("shipTime")))
            if shopInfo:
                status = shopInfo.get("shopStatus")
                if status == 0:
                    status = 1
                else:
                    status = 0
                shipTime = shopInfo.get("shipTime")
        except:
            logger.warning(traceback.format_exc())
            logger.info("{}mode1获取异常!".format(shopId))
        res = getmode1(int(shopId), int(shopType))
    newCusPrice = getNewCustomPrice(int(shopType), shopId)
    if res:
        res['status'] = status
        res['shipTime'] = shipTime
        res['newCusPrice'] = newCusPrice
        response = dict(code=200, message="获取成功", data=res)
    else:
        res = {"budget": "", "balance": "", "orderRate": '', "enterRate": '', "serviceDay": '', 'serviceStart': '',
               'serviceEnd': '', "status": status, "shipTime": shipTime, "newCusPrice": newCusPrice}
        response = dict(code=200, message="获取失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode2get")
def mode2get():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    suggestBudget = ''
    suggestTargetExposure = ''
    try:
        result = getmode2(shopId, int(shopType))
        if result:
            suggestBudget = result.get("budget")
            suggestTargetExposure = result.get("targetExposure")
    except:
        logger.warning(traceback.format_exc())
        logger.info("mode2获取异常!")
    res = getmode2(shopId, int(shopType))
    if res:
        res["suggestBudget"] = suggestBudget
        res["suggestTargetExposure"] = suggestTargetExposure
        response = dict(code=200, message="获取成功", data=res)
    else:
        res = {"budget": '', "targetExposure": '', "busyMaxPrice": '', "busyMinPrice": '',
               "idleMaxPrice": '', "idleMinPrice": '', "adTimeList": [], "shipTimeList": [],
               "busyTimeList": [], "status": '', "suggestBudget": suggestBudget, 'timeList':[],
               'suggestTargetExposure': suggestTargetExposure}
        response = dict(code=200, message="获取失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode2set")
def mode2set():
    shopId = request.values.get("shopId")
    shopType = int(request.values.get("shopType"))
    shopId = decryptShopId(shopId, shopType)
    targetExposure = request.values.get("targetExposure")
    budget = request.values.get("budget")
    adTime = request.values.get("adTime")
    busyTime = request.values.get("busyTime")
    busyMaxPrice = request.values.get("busyMaxPrice")
    busyMinPrice = request.values.get("busyMinPrice")
    idleMaxPrice = request.values.get("idleMaxPrice")
    idleMinPrice = request.values.get("idleMinPrice")
    immediate = request.values.get("immediate")
    # status = request.values.get("status")
    data = {"shopId": shopId,
            "shopType": shopType,
            "targetExposure": targetExposure,
            "budget": budget,
            "adTime": adTime,
            "busyTime": busyTime,
            "busyMaxPrice": busyMaxPrice,
            "busyMinPrice": busyMinPrice,
            "idleMaxPrice": idleMaxPrice,
            "idleMinPrice": idleMinPrice,
            "immediate": int(immediate),
            }

    res = setmode2(data)
    shopAccount, dbsAdTime = getAccountByIdAndShopType(shopId ,shopType)
    #更新店铺的参数
    if shopType == 1:
        kwargs = dict({"mtaccount":shopAccount, "mtbudget": budget})
    else:
        kwargs = dict({"eleaccount": shopAccount, "elebudget": budget})
    updShopInfo(**kwargs)
    #根据当前参数生成计划
    try:
        """ nextExposureRate = getNextExposureRate(account, int(shopType))
                deleteTodayTarget(account, int(immediate))
                data = dataPrepare4setTarget(account, adTime, shopType, targetExposure, budget, int(immediate))
                setTargetexposurePer4Web(data, shopType,nextExposureRate)"""
        nextExposureRate = getNextExposureRate(shopAccount, shopType)
        deleteTodayTarget(shopAccount, int(1))
        data = dataPrepare4setTarget(shopAccount, dbsAdTime, shopType, targetExposure, budget, 1)
        setTargetexposurePer4Web(data,shopType, nextExposureRate)
    except:
        logger.debug(traceback.format_exc())
        logger.info(shopAccount + "生成计划失败")

    if res:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode3get")
def mode3get():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    res = getmode3(shopId, int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        res = {"status": '', "curbidList": []}
        response = dict(code=200, message="获取失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode3set")
def mode3set():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    # status = int(request.values.get("status"))
    curbidList = request.values.get("curbidList")
    res = setmode3(shopId, int(shopType), curbidList)
    if res:
        response = dict(code=200, message="获取成功", data=1)
    else:
        response = dict(code=200, message="获取失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode4get")
def mode4get():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    res = getmode4(shopId, int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=200, message="获取失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/mode4set")
def mode4set():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    # status = int(request.values.get("status"))
    status = 1
    res = setmode4(shopId, int(shopType), status)
    if res:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/newAddShop", methods=["POST"])
def newAddShop():
    cookies = request.json.get("cookies")
    shopName = request.json.get("shopName")
    account = request.json.get("account")
    bid = request.json.get("bid", "")
    res = saveShop(cookies, shopName, account, bid)
    if res and not res.get("oldShop"):
        shopId = res.get("shopId")
        shopType = res.get("shopType")
        try:
            result = setSuggestParamLoad(shopId, shopType)
            suggestBudget = result.get("budget")
            suggestTargetExposure = result.get("targetExposure")
            suggestMaxPrice = result.get("maxPrice")
            suggestMinPrice = result.get("minPrice")
        except:
            logger.info(traceback.format_exc())
            logger.info("shopId:{}".format(shopId))
            logger.info("获取建议值出错")
        try:
            shopCookies = getShopCookieByShopId(shopId, shopType)
            shopInfo = getMOrEBsaeInfo(shopType, shopCookies,None)
            shipTime = shopInfo.get("date").get("shipTime")
            updShopInfoNew(**dict(shopId=shopId, shopType=shopType, shipTime=shipTime))
            setNewShopBaseInfo(shopId, shopType, account, shopCookies, suggestBudget, suggestTargetExposure,
                               suggestMaxPrice, suggestMinPrice, shipTime)
        except:
            logger.info(traceback.format_exc())
            logger.info("shopId:{}".format(shopId))
            logger.info("基本信息更新出错")
        ##划分闲时忙时

        # try:
        #     setBusyandIdle(shopId, shopType, suggestMaxPrice, suggestMinPrice)
        # except:
        #     logger.info(traceback.format_exc())
        #     logger.info("{}闲时忙时划分出错".format(shopId))

        try:
            getAllShopLastDayReportData(shopId)
        except:
            logger.info(traceback.format_exc())
            logger.info("{}获取报告数据出错".format(shopId))


        try:
            addBusinessInfo(shopId, shopType, cookies)
        except:
            logger.info(traceback.format_exc())
            logger.info("{}获取店铺30天的数据出错".format(shopId))


    if res:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/shop/addNewWeb")
def setShop():

    onlypara = int(request.values.get("onlypara"))
    now = int(request.values.get("now"))

    account = request.values.get("account")
    shopType = int(request.values.get("shopType"))

    targetExposure = int(request.values.get("targetExposure"))
    budget = int(request.values.get("budget"))
    adTime = request.values.get("adTime")

    data = dict(
        account = account,
        shopType = shopType,
        targetExposure = targetExposure,
        budget = budget,
        adTime = adTime,
        shopId = request.values.get("shopId"),
        controlRate = request.values.get("controlRate"),
        baseRate = request.values.get("baseRate"),
        idleMinPrice = request.values.get("idleMinPrice"),
        busyMaxPrice = request.values.get("busyMaxPrice"),
        busyMinPrice = request.values.get("busyMinPrice"),
        nextExposureRate = request.values.get("nextExposureRate"),
        idleExposureRate = request.values.get("idleExposureRate"),
        isenable = int(request.values.get("isenable")),
        guard = int(request.values.get("guard")),
        busyTimeLock = int(request.values.get("busyTimeLock")),
        historyMode = int(request.values.get("historyMode")),
        lock = int(request.values.get("lock")),
        percent = request.values.get("percent"),
        busyInfoList = request.values.get("busyInfoList"),
        idleInfoList = request.values.get("idleInfoList"),
        idleOrderRateList = request.values.get("idleOrderRateList"),
        idleMaxPriceList = request.values.get("idleMaxPriceList"),
        daysAvgPrice = request.values.get("daysAvgPrice"),
        busyOrderRate = request.values.get("busyOrderRate"),
    )
    try:
        saveSettings(data)
        if onlypara == 0:
            #只保存参数
            nextExposureRate = getNextExposureRate(account, shopType)
            deleteTodayTarget(account, now)
            data = dataPrepare4setTarget(account, adTime, shopType, targetExposure, budget, now)
            setTargetexposurePer4Web(data, shopType, nextExposureRate)

        response = dict(code=200, message="保存成功", data=None)
    except:
        logger.info(traceback.format_exc())
        response = dict(code=500, message="保存失败", data = None)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/newGetShopOrder", methods=['GET'])
def new_get_shop_order():
    response = config.RESPONSE
    sid = request.values.get("id")
    result = newGetShopOrder(sid=sid)
    response.update({"code": 200, "message": "成功", "data": result})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response



@app.route("/api/v1/chart/shop/newlogin", methods=["POST"])
def wechatLogin():
    shop_data = request.json.get("shopinfo")
    res = getShopidInfo(shop_data)
    response = dict(code=200, message="获取成功", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = '*'
    return response


@app.route("/api/v1/admin/shop/get7daysdata")
def get7data():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    res = getdata7(int(shopId), int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=200, message="获取失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/set7daysdata")
def set7data():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    daysData = request.values.get("daysData")
    res = setdata7(int(shopId), int(shopType), daysData)
    if res:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/shop/checkBug")
def checkShopBug():
    '''检查当前系统内未删除店铺的计划生成情况
    将该接口做成n条进程线，每一条主线中所有函数返回的提示跟账号进行绑定
    最后将错误信息进行返回'''
    # 调用service层进行服务
    result = serviceApiCheck()
    code = result.get("code", 0)
    if code == 6001:
        response = dict(code=500, message="检查失败", data=0)
    else:
        response = dict(code=200, message="检查完成", data=result.get("date", {}))
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/get7DaysPriceCount")
def get7DaysPriceCount():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    date = request.values.get("date")
    shopId = decryptShopId(shopId, int(shopType))
    res = getCurbidCount(shopId, int(shopType), date)
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=200, message="获取失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/getStatus")
def getShopStatusMode():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    res = getStatusMode(shopId, int(shopType))
    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        res = {"status2": 0, "status3": 0, "status4": 0}
        response = dict(code=500, message="获取失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/setStatus")
def setShopStatusMode():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    status2 = request.values.get("status2")
    status3 = request.values.get("status3")
    status4 = request.values.get("status4")
    res = setStatusMode(shopId, int(shopType), int(status2), int(status3), int(status4))
    if res:
        response = dict(code=200, message="设置成功", data=1)
    else:
        response = dict(code=200, message="设置失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/demo")
def getDemoShop():
    res = {"mtShop": {"shopId": "d3ea460f42899323b804305631937448", "shopType": 1},
           "eleShop": {"shopId": "e2862cb369650b0307a7ed75d27b22de", "shopType": 2}}

    if res:
        response = dict(code=200, message="获取成功", data=res)
    else:
        response = dict(code=500, message="获取失败", data=res)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/getNewAllShopBlance", methods=['GET'])
def getNewAllShopBlance():
    response = config.RESPONSE
    try:
        bid = request.values.get("bid")
        # day = request.values.get("day")
        result = getMyShopBlance(bid)
        if result == 1000:
            response.update({"code": 200, "message": "该账号没有绑定店铺", "data": False})
        if result == False:
            response.update({"code": 200, "message": "数据错误", "data": False})
        else:
            response.update({"code": 200, "message": "成功", "data": result})
    except:
        response.update({"code": 200, "message": "未知错误", "data": "fail"})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/localAdTime", methods=['GET'])
def lockAdTime():
    response = config.RESPONSE
    try:
        account = request.values.get("account", '')
        shopType = request.values.get("shopType", None)
        lock = request.values.get("lock", None)
        rest = None
        if account and shopType:
            rest = updShopInfoOfLock(account, int(shopType), int(lock))
        if rest:
            response.update({"code": 200, "message": "成功", "data": 'success'})
    except:
        response.update({"code": 500, "message": "未知错误", "data": "fail"})
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/app/shop/get", methods=["GET"])
def getappshop():
    '''
    获取商铺信息
    :param shopid:
    :return:
    '''
    try:
        shopId = request.values.get("shopId", "")
        originalShopId = shopId
        shopType = int(request.values.get("shopType", ""))
        app = int(request.values.get("app", 0))
        # 获取解密的shopId
        shopId = decryptShopId(shopId, shopType)
        # 获取日期
        date = request.values.get("date", "")
        if date:
            date = date + " 00:00:00"
        else:
            date = datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00"
        biddingInfo = getAppPriceCount(shopId, shopType, date, app)
        yesDateTime = (datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=-1)).strftime(
            "%Y-%m-%d %H:%M:%S")
        yesBiddingInfo = getAppPriceCount(shopId, shopType, yesDateTime, app)
        periodTarget = getPeriodTargetHour(shopId, shopType, date)
        orderResult = getPeriod7DaysOrderHour(originalShopId, shopType)
        sevenDaysAvgOrders = orderResult.get("hourOrderNumOfSeven")
        daysAvgNum = orderResult.get("orderNumOfSeven")
        shopBaseInfo = getShopBaseInfo(originalShopId, shopType)
        if not date:
            dateDay = datetime.datetime.now().strftime("%Y-%m-%d")
        else:
            dateDay = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
        headInfo = getYesOrderInfo(shopBaseInfo.get('account', ""), day=dateDay)
        if headInfo:
            headInfo = eval(headInfo)
            heads = {"item1": {"showCount": headInfo.get('ep', {}).get('o', None),
                               "targetExposure": headInfo.get('ep', {}).get('t', None)},
                     "item2": {"clickCount": headInfo.get('ck', {}).get('o', None),
                               "daysAvgClickCount": headInfo.get('ck', {}).get('s', None)},
                     "item3": {"currentCost": headInfo.get('cot', {}).get('p', None),
                               "todayBudget": int(headInfo.get('cot', {}).get('x', None)), "daysAvgCost": None},
                     "item4": {"avgPrice": headInfo.get('pc', {}).get('o', None),
                               "daysAvgPrice": headInfo.get('pc', {}).get('s', None)}}
        else:
            heads = getHeadInfos(int(shopId), int(shopType))
        table1 = {"hourPriceCounts": biddingInfo.get("hourPriceCounts", {}),
                  "allDayPriceCounts": biddingInfo.get("allDayPriceCounts", {}),
                  "masterData": biddingInfo.get("masterData", {}), "cost": None}
        table1Copy = {"hourPriceCounts": yesBiddingInfo.get("hourPriceCounts", {}),
                      "allDayPriceCounts": yesBiddingInfo.get("allDayPriceCounts", {}),
                      "masterData": yesBiddingInfo.get("masterData", {}), "cost": None}
        table2 = {"allExposure": None, "periodExposure": biddingInfo.get("periodExposure", []),
                  "periodTarget": periodTarget}
        table2Copy = {"allExposure": None, "periodExposure": yesBiddingInfo.get("periodExposure", []),
                      "periodTarget": None}
        table3 = {"allrealTimeOrder": None, "sevenDaysAvgOrders": sevenDaysAvgOrders,
                  "dayRealTimeOrder": biddingInfo.get("realTimeOrderList", [])}
        table4 = {"yesNum": None, "daysAvgNum": daysAvgNum}

        if date:
            today_time = dateDay
        else:
            today_time = datetime.datetime.now().strftime("%Y-%m-%d")
        # lastShopBidding = getShopBiddingReplenishNum(shopId, today_time, shopType)
        # yes_time=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d") + " 00:00:00"
        tommorrowList = datetime.datetime.strptime(today_time, "%Y-%m-%d")
        tommorrow_time = (tommorrowList + datetime.timedelta(days=+1)).strftime("%Y-%m-%d") + " 00:00:00"
        lastShopBidding = getShopBiddingYester(shopId, tommorrow_time, shopType)
        yesLastShopBidding = getShopBiddingYester(shopId, today_time + " 00:00:00", shopType)
        response = None
        if yesLastShopBidding and lastShopBidding:
            if lastShopBidding.id == yesLastShopBidding.id:
                response = dict(code=200, message="当前数据为空", data="")
        elif lastShopBidding == None:
            response = dict(code=200, message="当前数据为空", data="")
        if lastShopBidding:
            table1["cost"] = round(float(lastShopBidding.currentCost), 2)
            table2["allExposure"] = int(lastShopBidding.exposureNum)
            table3["allrealTimeOrder"] = int(lastShopBidding.realTimeOrder)
            if not yesLastShopBidding:
                yesNum = orderResult.get("yesNum")
                table4['yesNum'] = yesNum
            else:
                table4['yesNum'] = int(yesLastShopBidding.realTimeOrder)
            # headInfo={"exposure":lastShopBidding.exposureNum,"businessAmount":lastShopBidding.businessAmount,"realTimeOrder":lastShopBidding.realTimeOrder,"cost":round(float(lastShopBidding.todayBudget)*float(lastShopBidding.percentBudget),2)}
            data = {"table1": table1, "table2": table2, "table3": table3, "table4": table4, "headInfo": heads,
                    "shopBaseInfo": shopBaseInfo, "busyTime": biddingInfo.get("busyTime", []),
                    "table1Copy": table1Copy, "table2Copy": table2Copy}
            response = dict(code=200, message=config.RESPONSE_SUCCESS, data=data)
    except:
        response = dict(code=200, message="当前暂无数据", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/shop/mobilemode2set")
def mobilemode2set():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    busyMaxPrice = request.values.get("busyMaxPrice")

    budget = request.values.get("budget")
    status = request.values.get("status")
    res = mode2_set_for_mobile(shopId, int(shopType), busyMaxPrice, float(budget), int(status))
    if res:
        response = dict(code=200, message="保存成功", data=1)
    else:
        response = dict(code=200, message="保存失败", data=0)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


''' 报告接口'''
@app.route("/api/v1/report/get")
def getReportHeadInfo():

    # 运营报告
    shopId = request.values.get("shopId")
    originalShopId = shopId
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    day = request.values.get("date")
    nowTime = datetime.datetime.now().strftime("%H:%M")
    dayTime = datetime.datetime.now().strftime("%Y-%m-%d")

    redis = RedisConnect()
    if day == dayTime and nowTime < "08:00":
        # 如果是今天的运营报告,在8点之前返回昨天的运营报告，8点之后，查询redis，如果redis中有，返回redis的数据，如果没有自动生成
        yesterday = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
        result = redis.get(originalShopId + "-1-" + yesterday + "report")
        if result:
            result = eval(result)
            response = {"code": 200, "message": "获取成功", "data": result}
        else:
            response = {"code": 200, "message": "暂无数据", "data": ""}
    else:
        result = redis.get(originalShopId + "-1-" + day + "report")
        if result:
            result = json.loads(result)
            response = {"code": 200, "message": "获取成功", "data": result}
        else:
            res = getShopReportHeadInfo(shopId, 1, day)
            if res:
                response = {"code": 200, "message": "获取成功", "data": res}
            else:
                response = {"code": 200, "message": "暂无数据", "data": ""}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/runningreport/get")
def getReportData():
    # CPC曝光分析报告
    shopId = request.values.get("shopId")
    originalShopId = shopId
    shopType = request.values.get("shopType")
    shopId = decryptShopId(shopId, int(shopType))
    day = request.values.get("date")
    result = getReportInfo(shopId, 1, day)
    redis = RedisConnect()
    result = redis.get(originalShopId + "-1-" + day)
    if not result:
        result = getReportInfo(shopId, 1, day)
        if result:
            result["date"] = day
            response = {"code": 200, "message": "获取成功", "data": result}
        else:
            response = {"code": 200, "message": "暂无数据", "data": ''}
    else:

        result = eval(result)
        result["date"] = day
        response = {"code": 200, "message": "获取成功", "data": result}

    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/report/getExampleShop")
def getExampleShopData():
    # CPC实力店铺
    shopId = "89b4adfe6cd8df7f01d220378e858fc3"
    shopType = "1"
    day = request.values.get("date")
    shopInfo = {"shopId": shopId, "shopName": "恰似辣年火锅冒菜", "account": "wmqsln27101", "shopType": 1,
                "shopIcon": "http://p1.meituan.net/waimaipoi/f33cb1f32146d7d21376af6fa1e8cf4120831.jpg"}

    redis = RedisConnect()
    result = redis.get(shopId + "-" + shopType + "-" + day)
    if not result:
        response = {"code": 200, "message": "暂无数据", "data": ''}
    else:
        result = eval(result)
        result["shopInfo"] = shopInfo
        result["date"] = day
        response = {"code": 200, "message": "获取成功", "data": result}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/report/getExampleReport")
def getExampleReport():
    day = request.values.get("date")
    originalShopId = "89b4adfe6cd8df7f01d220378e858fc3"
    shopInfo = {"shopId": originalShopId, "shopName": "恰似辣年火锅冒菜", "account": "wmqsln27101", "shopType": 1,
                "shopIcon": "http://p1.meituan.net/waimaipoi/f33cb1f32146d7d21376af6fa1e8cf4120831.jpg"}

    redis = RedisConnect()
    result = redis.get(originalShopId + "-1-" + day + "getExampleReport")
    if not result:
        day = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -1)).strftime("%Y-%m-%d")
        result = redis.get(originalShopId + "-1-" + day + "getExampleReport")
        if result:
            result = eval(result)
            result["shopInfo"] = shopInfo
            result["date"] = day
            response = {"code": 200, "message": "获取成功", "data": result}
        else:
            response = {"code": 200, "message": "暂无数据", "data": ''}
    else:
        result = eval(result)
        result["shopInfo"] = shopInfo
        result["date"] = day
        response = {"code": 200, "message": "获取成功", "data": result}

    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/acquireIdleMaxPrice")
def acquireIdleMaxPrice():
    shopId = request.values.get("shopId")
    shopType = request.values.get("shopType")
    specialtime = request.values.get("specialtime")
    res = getIdleMaxPrice(int(shopId),int(shopType),specialtime)
    if res:
        response = {"code": 200, "message": "获取成功", "data": res}
    else:
        response = {"code": 500, "message": "获取失败", "data": ''}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/reportCheck")
def checkReport():
    res = reportCheck()
    response = {"code": 200, "message": "获取成功", "data": res}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/getReportData")
def getDataforReport():
    shopId = request.values.get("shopId")

    res = getYesReportData(int(shopId))
    if res:
        response = {"code": 200, "message": "获取成功", "data": 1}
    else:
        response = {"code": 500, "message": "获取失败", "data": 0}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/shop/getResearch")
def getDataforResearch():

    res = getResearchData()
    if res:
        response = {"code": 200, "message": "获取成功", "data": res}
    else:
        response = {"code": 500, "message": "获取失败", "data": 0}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/getBiddingData")
def getBiddingData():
    shopId = request.values.get("shopid")
    try:
        res = getBiddingsData(shopId)
        if res:
            response = {"code": 200, "message": "获取成功", "data": res}
        else:
            response = {"code": 500, "message": "获取失败", "data": ""}
    except:
        response = {"code": 500, "message": "获取失败", "data": ""}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/saveBiddingData")
def saveBiddingData():
    shopid = request.values.get("shopid")
    biddingdata = request.values.get("biddingdata")
    rest = saveBiddingDataToBases(shopid, biddingdata)
    if rest:
        response = {"code": 200, "message": "成功", "data": "1"}
    else:
        response = {"code": 500, "message": "失败", "data": "0"}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/getNewExposureRate")
def getNewExposureRate():
    account = request.values.get("account")
    shopType = request.values.get("shopType")
    shopId = request.values.get("shopId")
    adTime = request.values.get("adTime")
    targetexposure = request.values.get("targetExposure")
    controlRate = request.values.get("controlRate")
    baseRate = request.values.get("baseRate")
    budget = request.values.get("budget")

    res = getExposureRate(account, int(shopId), int(shopType), float(budget), adTime, int(targetexposure),float(controlRate),float(baseRate))
    if res > 0:
        response = {"code": 200, "message": "获取成功", "data": res}
    else:
        if res == -200:
            response = {"code": 500, "message": "该店铺现在没有计划，请重新生成", "data": None}
        else:
            response = {"code": 500, "message": "暂无可计算曝光比", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/createNewPlan")
def createNewPlan():
    account = request.values.get("account")
    shopType = request.values.get("shopType")
    adTime = request.values.get("adTime")
    budget = request.values.get("budget")
    targetExposure = request.values.get("targetExposure")
    updExposureRate = request.values.get("allExposureRate")
    idleExposureRate = request.values.get("idleExposureRate")
    try:
        deleteTodayTarget(account, 1)
        saveAllExposureRate(account,int(shopType),float(updExposureRate))
        nextExposureRate = getNextExposureRate(account,int(shopType))
        data = dataPrepare4setTarget(account, adTime, int(shopType), targetExposure, budget, 1)
        newSetTargetexposurePer4Web(data, shopType, float(idleExposureRate), float(updExposureRate), nextExposureRate)
        response = {"code": 200, "message": "重新生成计划成功", "data": None}
    except:
        logger.info(traceback.format_exc())
        response = {"code": 500, "message": "重新生成计划失败", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/checkip")
def checkIP():

    res = checkBuckupIp()
    if res :
        response = {"code": 200, "message": "获取备用IP成功", "data": res}
    else:
        response = {"code": 500, "message": "获取备用IP失败", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/admin/changeip")
def changeIP():
    ips = request.values.get("ips")
    iplist = ips.split(",")
    res = changeNewIp(iplist)
    if res :
        response = {"code": 200, "message": "更换IP成功", "data": res}
    else:
        response = {"code": 500, "message": "更换IP失败", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/admin/bindAccount")
def bindAccount():
    account = request.values.get("account")
    userName = request.values.get("userName")
    type = int(request.values.get("type"))
    res = bindShopAccount(account,userName, type)
    if res :
        response = {"code": 200, "message": "账号密码绑定成功", "data": None}
    else:
        response = {"code": 500, "message": "账号密码绑定失败或店铺不存在", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/chart/chagNewCusPrc")
def chagNewCusPrc():
    shopType = int(request.values.get("shopType"))
    shopId = request.values.get("shopId")
    shopId = decryptShopId(shopId, shopType)
    nowPrice = request.values.get("nowPrice")
    nowPrice = int(nowPrice)
    res = changeNewCustomPrice(shopId, shopType, nowPrice)
    if res :
        response = {"code": 200, "message": "价格修改为"+str(nowPrice), "data": None}
    else:
        response = {"code": 500, "message": "修改失败", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/chart/getAllTime")
def getAllTime():
    shopType = int(request.values.get("shopType"))
    shopId = request.values.get("shopId")
    shopId = decryptShopId(shopId, shopType)
    busyTime = request.values.get("busyTime")
    try:
        busyTime = eval(busyTime)
        allTime = getallTime(shopId, shopType, busyTime)
        response = {"code": 200, "message":"", "data":allTime}
    except:
        response = {"code": 500, "message":"时间格式错误", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response


@app.route("/api/v1/chart/bindAdminAndShop")
def bindAdShop():
    account = request.values.get("account")
    shops = request.values.get("shops")
    res = bindAdminShopApi(account, shops)
    if res == -1:
        response = {"code": 500, "message": "账号不存在", "data": None}
    elif res == -2:
        response = {"code": 501, "message": "数据插入错误", "data": None}
    elif res == -3:
        response = {"code": 502, "message": "店铺账号不存在", "data": None}
    else:
        response = {"code": 200, "message": "数据添加成功", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/chart/getShopInfo")
def getShopInfo():
    shopInfo = getAllShopInfo()
    response = {"code": 200, "message": "返回成功", "data": shopInfo}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/chart/mobilemode2setcopy")
def mobilemode2setcopy():
    shopId = request.values.get("shopId")
    shopType = int(request.values.get("shopType"))
    shopId = decryptShopId(shopId, shopType)
    timeList = request.values.get("timeList")
    budget = request.values.get("budget")
    res = setMobileMode2SetCopy(shopId, shopType, timeList, budget)
    if res :
        response = {"code": 200, "message": "设置成功", "data": res.get("account")}
    else:
        response = {"code": 500, "message": "设置失败", "data": None}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/shop/changeDeleted")
def changeDeleted():
    account = request.values.get("account")
    shopType = request.values.get("shopType")
    deleted = request.values.get("deleted")
    res = changeDeletedShopStatus(account, int(shopType), int(deleted))
    if res:
        response = dict(code=200, message="执行成功", data="")
    else:
        response = dict(code=500, message="执行失败", data="")
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

@app.route("/api/v1/shop/getIpInfo")
def getShopIpInfo():
    account = request.values.get("account")
    shopType = request.values.get("shopType")
    ipInfo = getMtShopIpInfo(account, int(shopType))
    if ipInfo == -1:
        response = dict(code=500, message="数据错误", data="")
    elif ipInfo == -2:
        response = dict(code=500, message="店铺ip不存在", data="")
    else:
        response = dict(code=200, message="执行成功", data=ipInfo)
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response